<template>
  <div class="w-full h-full flex flex-col">
    <h1 class="text-xl font-bold mb-4">HTTP 日志</h1>
    <div>
      <WebSocketStatusIndicator />
      <el-button class="bg-red-500 text-white ml-4" @click="clearAllLog">清除日志</el-button>
    </div>

    <div class="flex flex-row">
      <el-table :data="httpLogStore.logs" class="mt-4" max-height="800" @row-click="handleRowClick">
        <el-table-column type="index" label="序号" width="100" prop="index" />
        <el-table-column prop="request.url" label="URL" width="250">
          <template #default="scope">
            <el-tooltip :content="scope.row.request.url" placement="top" effect="light">
              <span class="truncate block">{{ scope.row.request.url }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="response.statusCode" label="状态码" width="100" />
        <el-table-column prop="request.method" label="方法" width="100" />
        <el-table-column prop="responseTime" label="响应时间(ms)" width="120">
          <template #default="scope"> {{ scope.row.responseTime }}ms </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button class="text-blue-500" @click.stop="handleCopyCurl(scope.row)"
              >复制Curl
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 新增 HttpLogDetail 组件 -->
      <HttpLogDetail ref="httpLogDetail" class="ml-4" style="width: 400px" />
    </div>
  </div>
</template>

<script setup>
import { ElMessage } from 'element-plus';
import { onUnmounted, ref } from 'vue';
import { useHttpLogStore } from './httpLogStore.ts';
import WebSocketStatusIndicator from '@components/WebSocketStatusIndicator.vue';
import HttpLogDetail from '@components/HttpLogDetail.vue';
import { onMounted } from 'vue-demi'; // 确保导入 HttpLogDetail 组件
import useClipboard from 'vue-clipboard3';

const httpLogStore = useHttpLogStore();
const selectedLog = ref(null); // 新增响应式变量用于存储选中的日志
const httpLogDetail = ref(null);
const { toClipboard } = useClipboard();
onMounted(() => {
  console.log('http-log-page onMounted');
  httpLogStore.unBindWebSocketListener();
  httpLogStore.setupWebSocketListener();
});
const handleRowClick = (row) => {
  selectedLog.value = row; // 设置选中的日志
  httpLogDetail.value.setRequestBean(row.request);
  httpLogDetail.value.setResponseBean(row.response);
};

function clearAllLog() {
  httpLogStore.clearLogs();
  ElMessage.success('清除日志成功');
}

const handleCopyCurl = (row) => {
  var curlCommand = `curl -X ${row.request.method} '${row.request.url}'`;

  // 添加 headers
  if (row.request.headers) {
    try {
      console.log('row.request.headers', row.request.headers);
      const headersObj = row.request.headers;
      console.log('headersObj', headersObj);
      for (const [key, value] of Object.entries(headersObj)) {
        curlCommand += ` -H '${key}: ${value}'`;
      }
    } catch (error) {
      console.error('Headers are not in valid JSON format.', error);
    }
  }

  // 添加 data (仅用于 POST 和 PUT)
  if ((row.request.method === 'POST' || row.request.method === 'PUT') && row.request.data) {
    try {
      console.log('row.request.data', row.request.data);
      const dataObj = row.request.data;
      console.log('dataObj', dataObj);
      curlCommand += ` -d '${JSON.stringify(dataObj)}'`;
    } catch (error) {
      console.error('Data is not in valid JSON format.', error);
    }
  }
  toClipboard(curlCommand);
  ElMessage.success('Curl 命令已复制到剪贴板');
};

onUnmounted(() => {
  // 清理操作（如果需要）
  // httpLogStore.logs = [];
});
</script>

<style scoped>
.truncate {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
